import requests
import time
from models.ai_config import AIConfig

class HealthChecker:
    """AI服务健康检查工具"""
    
    @staticmethod
    def check_ai_config_health(config_id):
        """检查单个AI配置的健康状态"""
        try:
            config = AIConfig.query.get(config_id)
            if not config:
                return {'healthy': False, 'error': '配置不存在'}
            
            start_time = time.time()
            
            # 根据不同提供商进行健康检查
            if config.provider == 'stable_diffusion':
                result = HealthChecker._check_stable_diffusion(config)
            elif config.provider == 'baidu':
                result = HealthChecker._check_baidu(config)
            elif config.provider == 'aliyun':
                result = HealthChecker._check_aliyun(config)
            else:
                result = {'healthy': True, 'message': '模拟服务正常'}
            
            response_time = time.time() - start_time
            
            # 更新配置的健康状态
            status = 'healthy' if result['healthy'] else 'down'
            config.update_health_status(status, response_time)
            
            return {
                'healthy': result['healthy'],
                'response_time': response_time,
                'message': result.get('message', ''),
                'error': result.get('error', '')
            }
            
        except Exception as e:
            return {'healthy': False, 'error': str(e)}
    
    @staticmethod
    def _check_stable_diffusion(config):
        """检查Stable Diffusion API健康状态"""
        try:
            # 简单的健康检查，发送最小请求
            headers = {
                'Authorization': f'Bearer {config.api_key}',
                'Content-Type': 'application/json'
            }
            
            # 使用engines端点进行健康检查
            engines_url = config.api_endpoint.replace('/text-to-image', '/engines/list')
            response = requests.get(engines_url, headers=headers, timeout=10)
            
            if response.status_code == 200:
                return {'healthy': True, 'message': 'Stable Diffusion API正常'}
            else:
                return {'healthy': False, 'error': f'API返回状态码: {response.status_code}'}
                
        except requests.Timeout:
            return {'healthy': False, 'error': 'API请求超时'}
        except Exception as e:
            return {'healthy': False, 'error': str(e)}
    
    @staticmethod
    def _check_baidu(config):
        """检查百度API健康状态"""
        try:
            # TODO: 实现百度API健康检查
            return {'healthy': True, 'message': '百度API健康检查（模拟）'}
        except Exception as e:
            return {'healthy': False, 'error': str(e)}
    
    @staticmethod
    def _check_aliyun(config):
        """检查阿里云API健康状态"""
        try:
            # TODO: 实现阿里云API健康检查
            return {'healthy': True, 'message': '阿里云API健康检查（模拟）'}
        except Exception as e:
            return {'healthy': False, 'error': str(e)}
    
    @staticmethod
    def check_all_configs():
        """检查所有AI配置的健康状态"""
        configs = AIConfig.query.filter_by(is_active=True).all()
        results = []
        
        for config in configs:
            result = HealthChecker.check_ai_config_health(config.id)
            results.append({
                'config_id': config.id,
                'config_name': config.name,
                'provider': config.provider,
                **result
            })
        
        return results

class ResponseFormatter:
    """API响应格式化工具"""
    
    @staticmethod
    def success(data=None, message='操作成功', code=200):
        """成功响应格式"""
        response = {
            'success': True,
            'code': code,
            'message': message
        }
        
        if data is not None:
            response['data'] = data
            
        return response
    
    @staticmethod
    def error(message='操作失败', code=400, details=None):
        """错误响应格式"""
        response = {
            'success': False,
            'code': code,
            'message': message
        }
        
        if details:
            response['details'] = details
            
        return response
    
    @staticmethod
    def paginated(items, total, page, per_page, message='获取成功'):
        """分页响应格式"""
        return {
            'success': True,
            'message': message,
            'data': {
                'items': items,
                'pagination': {
                    'total': total,
                    'page': page,
                    'per_page': per_page,
                    'pages': (total + per_page - 1) // per_page,
                    'has_next': page * per_page < total,
                    'has_prev': page > 1
                }
            }
        }